import datetime

from django.db.models import Sum

from databases.models import UserInfo, ConnectionRecord, ConnectionTypeRecord



def my_scheduled_job():
    print("my_scheduled_job",datetime.datetime.now())

def StopWearableDeviceTiming():
    """
    五个小时之前还没有结束的训练记录,设置为结束状态
    """
    _five_date = datetime.datetime.now() + datetime.timedelta(hours=-5)

    # print(ConnectionRecord.objects.filter(start_time__lt=_five_date, end_time__isnull=True).query)
    print("停止五个小时还没有停止的训练-start", datetime.datetime.now())
    _connections = ConnectionRecord.objects.filter(start_time__lt=_five_date, end_time__isnull=True)
    for __connection in _connections:
        _connection_type = ConnectionTypeRecord.objects.filter(start_time__lt=_five_date, end_time__isnull=True,
                                                               connect=__connection)
        for _type in _connection_type:
            _type.end_time = _type.start_time + datetime.timedelta(hours=5)
            _type.duration = (_type.end_time - _type.start_time).total_seconds()
            _type.save()
        __connection.end_time = __connection.start_time + datetime.timedelta(hours=5)
        __connection.duration = (__connection.end_time - __connection.start_time).total_seconds()
        __connection.avg_heart_rate = 0
        __connection.max_heart_rate = 0
        __connection.min_heart_rate = 0
        __connection.data_package = 0
        __connection.save()
    print("停止五个小时还没有停止的训练-end", datetime.datetime.now())

        # _userinfo = UserInfo.objects.get(pk=__connection.user_id)
        # _connections = ConnectionRecord.objects.filter(user=_userinfo)
        # if _userinfo.medals is None:
        #     if len(_connections) >= 30:
        #         _userinfo.medals = '3'
        #     else:
        #         pass
        # else:
        #     if '3' in _userinfo.medals:
        #         pass
        #     else:
        #         if len(_connections) >= 30:
        #             _userinfo.medals = _userinfo.medals + ',3'
        #         else:
        #             pass
        # _userinfo.total_sport_time = _userinfo.total_sport_time + __connection.duration
        # _userinfo.total_week_sport_time = _userinfo.total_week_sport_time + __connection.duration
        # _userinfo.total_day_sport_time = _userinfo.total_day_sport_time + __connection.duration
        # _userinfo.save()


def ClearDaySportTime():
    # 清除每日统计 修改成统计今天的数据
    print("清除每日统计-start", datetime.datetime.now())
    _today = datetime.datetime.today()
    # 定位到凌晨
    _today = datetime.datetime(_today.year, _today.month, _today.day, 0, 0, 0)
    _userInfos = ConnectionRecord.objects.filter(duration__lt=18000, end_time__gte=_today).values(
        "user_id").annotate(
        day_time=Sum("duration")).values("user_id", "day_time")
    UserInfo.objects.all().update(total_day_sport_time=0)
    for __userInfo in _userInfos:
        _userInfo = UserInfo.objects.get(pk=__userInfo['user_id'])
        _userInfo.total_day_sport_time = __userInfo['day_time']
        _userInfo.save()
    print("清除每日统计-end", datetime.datetime.now())


def UpdateWeekSportTime():
    """
    更新最近七天的运动时间
    """
    print("更新每周运动时间-start", datetime.datetime.now())
    _before7 = datetime.datetime.now() - datetime.timedelta(days=7)
    _userInfos = ConnectionRecord.objects.filter(duration__lt=18000, end_time__gte=_before7).values(
        "user_id").annotate(
        week_time=Sum("duration")).values("user_id", "week_time")
    UserInfo.objects.all().update(total_week_sport_time=0)
    for __userInfo in _userInfos:
        _userInfo = UserInfo.objects.get(pk=__userInfo['user_id'])
        _userInfo.total_week_sport_time = __userInfo['week_time']
        _userInfo.save()
    print("更新每周运动时间-end", datetime.datetime.now())


def UpdateLuckyDay():
    print("更新用户运动天数-start", datetime.datetime.now())
    from django.db import connection, transaction
    cursor = connection.cursor()
    cursor.execute(
        "SELECT	user_id, count(1) FROM "
        "(SELECT user_id,DATE_FORMAT(end_time, '%y-%m-%d') "
        "formate_date FROM connection_record GROUP BY user_id, "
        "DATE_FORMAT(end_time, '%y-%m-%d')	) AS t GROUP BY	user_id ")
    rows = cursor.fetchall()
    for row in rows:
        user_info = UserInfo.objects.get(pk=row[0])
        user_info.sport_day = row[1]
        user_info.save()
    print("更新用户运动天数-end", datetime.datetime.now())
